package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.PersonalScoreListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.PersonalRank;
import com.isunland.managesystem.entity.PersonalRankOriginal;
import com.isunland.managesystem.entity.PersonalScoreList;
import com.isunland.managesystem.entity.PersonalScoreList.PersonalScoreContent;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * Created by wu on 2016/4/21.
 * 获取个人奖惩积分列表
 */
public class PersonalScoreListFragment extends BaseListFragment {

  private static final int REQUEST_SEARCH = 0;
  private TextView tvContent1;
  private TextView tvTitle1;
  private TextView tvContent2;
  private TextView tvTitle2;
  private LinearLayout llScore3;
  private PersonalScoreListAdapter mAdapter;
  private String mStartDate;
  private String mEndDate;
  private CurrentUser mUser;
  private Date date;//结束时间戳
  private int mPage = 1;// 请求第几页的数据.

  @Override public void onStart() {
    volleyPostGetRank();
    super.onStart();
  }

  /**
   * 当前登录人积分排名
   */
  protected void volleyPostGetRank() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SCORE_RANK_SELF);
    HashMap<String, String> params = new HashMap<>();
    params.put("ifapp", "true");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        PersonalRankOriginal original = new Gson().fromJson(arg0, PersonalRankOriginal.class);
        PersonalRank content = original.getRows();
        if (content != null) {
          String monthranking = content.getMonthranking();//月度排名
          String yearranking = content.getYearranking();//年度排名
          tvContent1.setText(yearranking);
          tvContent2.setText(monthranking);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
      }
    });
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    mUser = CurrentUser.newInstance(getActivity());
    mStartDate = MyDateUtil.getFirstDay();
    mEndDate = MyDateUtil.dateToString(MyDateUtil.getAfterDay(MyDateUtil.getLastDayDate(), 1),
        MyDateUtil.TYPE_DATE);//最后一天向后推一天
    date = MyDateUtil.getLastDayDate();
    super.onCreate(savedInstanceState);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.view_rew_score, null, false);
    tvTitle1 = (TextView) header.findViewById(R.id.tv_title1);
    tvContent1 = (TextView) header.findViewById(R.id.tv_content1);
    tvTitle2 = (TextView) header.findViewById(R.id.tv_title2);
    tvContent2 = (TextView) header.findViewById(R.id.tv_content2);
    llScore3 = (LinearLayout) header.findViewById(R.id.ll_score3);
    tvTitle1.setText("你的年度排名");
    tvTitle2.setText("你的月度排名");
    llScore3.setVisibility(View.GONE);

    mListview.addHeaderView(header);
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
  }

  @Override public String getUrl() {
    return ApiConst.ULR_GET_PERSONAL_SCORE;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();

    params.put("inStaffId", mUser.getJobNumber());
    params.put("inStaffName", mUser.getRealName());
    params.put("beginregDate", mStartDate);
    params.put("endregDate", mEndDate);
    params.put("memberCode", mUser.getMemberCode());
    params.put("dataStatus", "publish");
    params.put("orderField", "in_Staff_Name,order_no");
    params.put("orderSeq", "desc");
    params.put("page", mPage + "");
    params.put("pageSize", "20");
    return params;
  }

  @Override public void resolveResponse(String json) {
    PersonalScoreList rows = new Gson().fromJson(json, PersonalScoreList.class);
    List<PersonalScoreContent> list = rows.getRows();

    if (list != null && list.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
    }
    setAdapter(list);
  }

  private void setAdapter(List<PersonalScoreContent> list) {
    if (list == null) {
      list = new ArrayList<>();
    }
    if (mAdapter == null) {
      mAdapter =
          new PersonalScoreListAdapter(getActivity(), list, PersonalScoreListAdapter.PERSONAL);
      setListAdapter(mAdapter);
      return;
    }
    if (mPage == 1) {
      mAdapter.clear();
    }
    mAdapter.addAll(list);
    ((PersonalScoreListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    //避免点击header时的getitem出现-1的情况.
    if (position < mListview.getHeaderViewsCount()) return;
    PersonalScoreContent content = mAdapter.getItem(position - l.getHeaderViewsCount());
    Intent intent = new Intent(getActivity(), PersonalScoreDetailActivity.class);
    intent.putExtra(PersonalScoreDetailFragment.EXTRA_VALUE, content);
    intent.putExtra(PersonalScoreDetailFragment.EXTRA_TYPE, PersonalScoreDetailFragment.PERSONAL);
    startActivity(intent);
    super.onListItemClick(l, v, position, id);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_query:
        Intent intent = new Intent(getActivity(), PersonalOrAssignSearchActivity.class);
        intent.putExtra(PersonalOrAssignSearchFragment.EXTRA_STARTTIME, mStartDate);
        //                intent.putExtra(PersonalOrAssignSearchFragment.EXTRA_ENDTIME,mEndDate);
        intent.putExtra(PersonalOrAssignSearchFragment.EXTRA_DATE, date);
        intent.putExtra(PersonalOrAssignSearchFragment.EXTRA_TYPE,
            PersonalOrAssignSearchFragment.PERSONAL);
        startActivityForResult(intent, REQUEST_SEARCH);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    PullToRefreshBase.Mode mode = refreshView.getCurrentMode();
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_START)) {

      mPage = 1;
    }
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == REQUEST_SEARCH && data != null) {
      mStartDate = data.getStringExtra(PersonalOrAssignSearchFragment.EXTRA_STARTTIME);
      //            mEndDate = data.getStringExtra(PersonalOrAssignSearchFragment.EXTRA_ENDTIME);

              /*结束时间*/
      Date mdate = (Date) data.getSerializableExtra(PersonalOrAssignSearchFragment.EXTRA_DATE);

      //noinspection deprecation
      mEndDate = MyDateUtil.dateToString(mdate, MyDateUtil.TYPE_DATE);

      date = MyDateUtil.getBeforDay(mdate, 1);//向前推一天
      LogUtil.i("推后endDate====" + mEndDate);
    }
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
    mPage = 1;
    volleyPost();
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    super.onActivityResult(requestCode, resultCode, data);
  }
}
